package com.fancon.android.gardenjokesx.widget;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fancon.android.core.IFanconGlobalState;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.activity.FollowxActivity;
import com.fancon.android.gardenjokesx.dialog.M04MDialog;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.StringUtil;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.ImageCacheView;

public class ProfileDetailHeaderView extends LinearLayout implements
		OnClickListener {
	private Context mContext;
	private String currentUserId;
	private String mViewedUserId;
	private Boolean isAuth = false;
	private User user;

	private ImageCacheView avatar;
	private TextView postCount, followersCount, followingCount, status;
	private Button follow;
	private View followers, followings, avatarx;

	public ProfileDetailHeaderView(final Context context) {
		super(context);
		mContext = context;
		// TODO Auto-generated constructor stub
		LayoutInflater layoutInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		layoutInflater.inflate(R.layout.row_profile_header, this);

		followers = findViewById(R.id.row_profile_header_container_followers);
		followings = findViewById(R.id.row_profile_header_container_following);

		avatar = (ImageCacheView) findViewById(R.id.row_profile_header_imageview);
		postCount = (TextView) findViewById(R.id.row_profile_header_textview_photos_count);
		followersCount = (TextView) findViewById(R.id.row_profile_header_textview_followers_count);
		followingCount = (TextView) findViewById(R.id.row_profile_header_textview_following_count);
		status = (TextView) findViewById(R.id.row_profile_header_textview_following_status);
		follow = (Button) findViewById(R.id.row_profile_header_button_follow);
		avatarx = findViewById(R.id.avatar);
		avatarx.setOnClickListener(this);
		follow.setOnClickListener(this);
		followers.setOnClickListener(this);
		followings.setOnClickListener(this);
		avatarx.setOnClickListener(this);
	}

	public void loadUserProfile(User user, String currentUserId,
			String mViewedUserId) {
		if (user != null) {
			this.user = user;
			this.currentUserId = currentUserId;
			this.mViewedUserId = mViewedUserId;
			this.isAuth = currentUserId.equals(mViewedUserId) ? true : false;
			if (isAuth) {
				View followFrame = findViewById(R.id.row_profile_header_viewgroup_following);
				followFrame.setVisibility(View.GONE);
			} else {
				View followFrame = findViewById(R.id.row_profile_header_viewgroup_following);
				followFrame.setVisibility(View.VISIBLE);
			}
			// Check for Block User
			if (user != null && user.isBlock_user()) {
				// nothing to see here
				// come back
				AlertDialog alertDialog;
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
				// builder.setTitle("Sorry you can't view this user");
				builder.setMessage(mContext
						.getString(R.string.common_block_message));
				builder.setPositiveButton("ok",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int arg1) {
								((Activity) mContext).finish();
								dialog.dismiss();
							}
						});
				builder.setCancelable(false);
				alertDialog = builder.create();
				alertDialog.show();
				return;
			}
		}
		postCount.setText(String.valueOf(user.getNumber_post()));
		followersCount.setText(String.valueOf(user.getNumber_follower()));
		followingCount.setText(String.valueOf(user.getNumber_following()));
		postCount.setText(String.valueOf(user.getNumber_post()));
		avatar.loadImage(StringUtil.processImageLink(user.getUrl_image()));
		if (user.isIs_following()) {
			status.setText(mContext.getString(R.string.following_text));
			follow.setText(mContext.getString(R.string.common_btn_following));
		} else {
			status.setText(mContext.getString(R.string.followx_text));
			follow.setText(mContext.getString(R.string.common_btn_follow));
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (user != null) {
			Boolean isAccess = (!user.isIs_private()) || isAuth;
			if (v == avatarx) {
				if (isAccess) {
					Dialog settingPicture = new M04MDialog(mContext, user);
					settingPicture.show();
				} else {
					privateAlert();
				}
			} else if (v == followers) {
				if (isAccess) {
					Intent intent = new Intent(mContext, FollowxActivity.class);
					intent.putExtra("is_following", "false");
					intent.putExtra(Constant.SCREEN_ID, Constant.M04);
					intent.putExtra(Constant.USER_ID_VIEW, mViewedUserId);
					mContext.startActivity(intent);
				} else {
					privateAlert();
				}
			} else if (v == followings) {
				if (isAccess) {
					Intent intent = new Intent(mContext, FollowxActivity.class);
					intent.putExtra("is_following", "true");
					intent.putExtra(Constant.SCREEN_ID, Constant.M04);
					intent.putExtra(Constant.USER_ID_VIEW, mViewedUserId);
					mContext.startActivity(intent);
				} else {
					privateAlert();
				}
			} else if (v == follow) {
				if (isAccess) {
					FollowRequest followReq;
					if (!user.isIs_following()) {
						user.setNumber_following(user.getNumber_following()+1);
						followingCount.setText(String.valueOf(user.getNumber_following()));
						status.setText(mContext
								.getString(R.string.following_text));
						follow.setText(mContext
								.getString(R.string.common_btn_following));
						followReq = new FollowRequest("m04gx",
								(Activity) mContext, "true");
					} else {
						user.setNumber_following(user.getNumber_following()-1);
						followingCount.setText(String.valueOf(user.getNumber_following()));
						status.setText(mContext
								.getString(R.string.followx_text));
						follow.setText(mContext
								.getString(R.string.common_btn_follow));
						followReq = new FollowRequest("m04gx",
								(Activity) mContext, "false");
					}
					
					((IFanconGlobalState) mContext).getRequestQueue()
							.addRequest(followReq);
				} else {
					privateAlert();
				}
			}
		}
	}

	/**
	 * Access restricted when user is private pop up show
	 */
	private void privateAlert() {
		AlertDialog alertDialog;
		AlertDialog.Builder builder = null;

		builder = new AlertDialog.Builder(mContext);
		builder.setTitle("");
		builder.setMessage(mContext.getString(R.string.m04_private_click));
		builder.setPositiveButton(mContext.getString(R.string.common_close),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int arg1) {
						dialog.dismiss();
					}
				});

		builder.setCancelable(false);
		alertDialog = builder.create();
		alertDialog.show();
	}

	class FollowRequest extends RequestUI {
		private Activity context;
		private String isFollowing;
		private String json;

		public FollowRequest(Object key, Activity activity, String isFollowing) {
			super(key, activity);
			// TODO Auto-generated constructor stub
			context = activity;
			this.isFollowing = isFollowing;
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs
					.add(new BasicNameValuePair("user_id", currentUserId));
			nameValuePairs.add(new BasicNameValuePair("following_user_id",
					mViewedUserId));
			nameValuePairs.add(new BasicNameValuePair("is_following",
					isFollowing));
			GardenJokesApiConnect api = new GardenJokesApiConnect(context);
			json = api.execPost(context, GardenJokesApiConnect.GROUP_S,
					"registerFollowingUser", nameValuePairs);
			Log.v("StringResult", json);
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			Boolean ok = false;
			JSONObject result = new JSONObject();
			try {
				result = new JSONObject(json);
				if (result.opt("is_success") != null) {
					ok = result.getBoolean("is_success");
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (ok) {
				// change current status
				user.setIs_following(!user.isIs_following());
			} else {
				// reset text status
				if (user.isIs_following()) {
					user.setNumber_following(user.getNumber_following()+1);
					followingCount.setText(String.valueOf(user.getNumber_following()));
					
					status.setText(mContext.getString(R.string.following_text));
					follow.setText(mContext
							.getString(R.string.common_btn_following));
				} else {
					user.setNumber_following(user.getNumber_following()-1);
					followingCount.setText(String.valueOf(user.getNumber_following()));
					
					status.setText(mContext.getString(R.string.followx_text));
					follow.setText(mContext
							.getString(R.string.common_btn_follow));
				}
				try {
					Toast.makeText(context, result.getString("message"), 1000)
							.show();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}
}
